package com.gem.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gem.back.entity.*;
import com.gem.back.service.*;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Description:后台主页控制器
 */
@Controller
@RequestMapping("/a")
public class AoaIndexController {
    @Autowired
    private IAoaUserService iAoaUserService;
    @Autowired
    private IAoaRoleService iAoaRoleService;
    @Autowired
    private IAoaSysMenuService iAoaSysMenuService;
    @Autowired
    private IAoaDeptService iAoaDeptService;
    @Autowired
    private IAoaPositionService iAoaPositionService;
    @Autowired
    private IAoaNoticeListService aoaNoticeListService;
    @Autowired
    private IAoaProcessListService aoaProcessListService;
    @Autowired
    private IAoaAttendsListService aoaAttendsListService;
    @Autowired
    private IAoaTypeListService aoaTypeListService;
    @Autowired
    private IAoaUserLoginRecordService aoaUserLoginRecordService;



    @RequestMapping("/index")
    public String index(Model model, HttpSession session, HttpServletRequest request) throws UnknownHostException {
        //读取当前登录成功的角色，并根据角色加载菜单
        //读取spring security用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
        .getAuthentication()
        .getPrincipal();
        AoaUser aoaUser = iAoaUserService.findUserByName(userDetails.getUsername());
        Integer userId = aoaUser.getUserId();
        session.setAttribute("userId",userId);
        //读取当前用户的部门
        AoaDept aoaDept = iAoaDeptService.findDeptByName(userDetails.getUsername());
        AoaRole aoaRole = iAoaRoleService.findRoleByName(userDetails.getUsername());
        AoaPosition aoaPosition = iAoaPositionService.findPositionByName(userDetails.getUsername());

        //读取当前用户管理的菜单
        List<AoaSysMenu> menuList = iAoaSysMenuService.findListByName(userDetails.getUsername());

        //记录用户登录日志
        AoaUserLoginRecord userLoginRecord = new AoaUserLoginRecord();
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        Version version = browser.getVersion(request.getHeader("User-Agent"));
        String info = browser.getName() + "/" + version.getVersion();
        String ip= InetAddress.getLocalHost().getHostAddress();
        userLoginRecord.setBrowser(info);
        userLoginRecord.setIpAddr(ip);
        userLoginRecord.setLoginTime(LocalDateTime.now());
        userLoginRecord.setUserId(Long.valueOf(userId.toString()));
        aoaUserLoginRecordService.save(userLoginRecord);

        model.addAttribute("menus",menuList);
        model.addAttribute("aoaUser",aoaUser);
        model.addAttribute("aoaDept",aoaDept);
        model.addAttribute("aoaRole",aoaRole);
        model.addAttribute("aoaPosition",aoaPosition);
        menuList.forEach(System.out::println);
        return "index";
    }

    //快捷入口页面
    @RequestMapping("/control")
    public String control(@SessionAttribute("userId") Integer id,Model model){
        //通知列表数
        Integer noticeCount = aoaNoticeListService.getMyTotal("",id );
        //流程申请数
        Integer processCount = aoaProcessListService.getTotal(id);
        //根据用户id查询当前通知列表
        List<AoaNoticeList> noticeLists = aoaNoticeListService.findMyNoticeById(id);

        //列举不超过5条审批记录
        QueryWrapper<AoaProcessList> processListQueryWrapper = new QueryWrapper<>();
        processListQueryWrapper.orderByDesc("apply_time");
        processListQueryWrapper.eq("process_user_id",id);
        processListQueryWrapper.last("limit 5");
        List<AoaProcessList> processLists = aoaProcessListService.list(processListQueryWrapper);

        //获取当前签到信息
        getSiginInfo(model,id);

        model.addAttribute("noticeCount",noticeCount);
        model.addAttribute("noticeLists",noticeLists);
        model.addAttribute("processCount",processCount);
        model.addAttribute("processLists",processLists);
        return "systemControl/control";
    }

    //签到信息
    private void getSiginInfo(Model model, Integer userId) {
        // 显示用户当天最新的记录
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String nowDate = sdf.format(date);

        QueryWrapper<AoaAttendsList> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("attends_time",nowDate);
        queryWrapper.eq("attends_user_id",userId);
        queryWrapper.orderByDesc("attends_time");
        queryWrapper.last("limit 1");
        AoaAttendsList attends = aoaAttendsListService.getOne(queryWrapper);
        if (attends != null) {
            AoaTypeList type = aoaTypeListService.getById(attends.getType());
            model.addAttribute("type", type.getTypeName());
        }
        model.addAttribute("attends", attends);
    }
}
